<?php
/**
 * Created by PhpStorm.
 * User: czm
 * Date: 2019-07-17
 * Time: 15:52
 */
namespace app\index\controller;


use think\Controller;
use think\Validate;
use think\Session;
use think\Db;
use think\Loader;
use lib\Ucpaas;

class Register extends Controller
{
    public function register()
    {
        if (request()->isPost())
        {
            $data= input('post.');
            $a = $data['phone'];
            $rule = [
                'name'  =>'require|max:25',
                'phone'    =>'regex:/^[1][3456789][0-9]{9}$/',
                'password' =>'require|length:6,32'
            ];
            $msg = [
                'name'  =>'姓名选项不能为空',
                'phone'    =>'手机号码不符合规格',
                'password' =>'密码不符合规则'
            ];
            $data = [
                'name'  => $data['msg']['name'],
                'phone'    =>$data['msg']['phone'],
                'password' =>md5($data['msg']['password'])
            ];
            $validate = new Validate($rule, $msg);
            $result   = $validate->check($data);
            if (!$result) {
                echo  $validate->getError();
                exit;
            }
            //手机号码已经注册
            $aa = Db::name('user')->where('phone',$a)->find();
            if ($aa)
            {
                $dat = ['code' => 402, 'msg' => '手机号已存在'];
                return json_encode($dat, TRUE);
            }
            if (Db::name('user')->insert($data))
            {
                $dat = ['code' => 200, 'msg' => '注册成功'];
                return json_encode($dat);

            }else{
                $dat = ['code' => 403, 'msg' => '注册失败'];
                return json_encode($dat, TRUE);
            }
//            $User = Loader::model('User');
//            $where = [
//                'phone'=> $data['phone'],
//                'type' => $data['type']
//            ];
//            if ($res = $User->where($where)->find()) {
//                return show(402);
//            }
//            if($user_id = $User->insertGetId($data)) {
//                Session::set('name',$data['name']);
//                Session::set('id',$user_id);
//                return show(200,'',$user_id);
//            }

        } else {
            return json_encode(403);
        }
    }

    //验证码
    public function send()
    {
        if (!($phone = input('phone'))) {
            return show(400);
        }
        //判断手机号是否注册
        $User = Loader::model('user');
        if($User->where('phone',$phone)->find()) {
            return show(402);
        }

        Loader::import('Ucpaas.php', EXTEND_PATH);
        //初始化必填
        $options['phonesid'] = 'da776c1deccc22c682efce0cdf088ca2';
        $options['token'] = 'ad86c5251867b87a40f9602176c2b854';
        //实例化Ucpaas
        $Ucpaas = new Ucpaas($options);
        //接入产品
        //短信验证码（模板短信）,默认以65个汉字（同65个英文）为一条（可容纳字数受您应用名称占用字符影响），超过长度短信平台将会自动分割为多条发送。分割后的多条短信将按照具体占用条数计费。
        $appId = "e8501ac72bd0469cb5f0f3cc06030e06";
        //对象终端
        $to = $phone; //应该是获取到的手机号码
        //短信模板id
        // $templateId = "421874";
        //参数 (验证码)
        // $param = rand(10000, 90000);
        $param = '123456';
        //原样格式
//         $data = $Ucpaas->templateSMS($appId, $to, $templateId, $param);
        // $data = json_decode($data, true);
        $data['resp']['respCode'] = '000000';
        if ($data['resp']['respCode'] == '000000') {
            Session::set('send_'.$phone,$param,60);
            return show(200,'',$param);
        }
        return show(403);
    }

    public function registera()
    {
        $phone = trim(input('phone'));
        $password = trim(input('password'));
        $repassword = trim(input('repassword'));

        if ($phone)
        {
            $rule = [
                'password' => 'require|/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,18}$/',
            ];
            $msg = [
                'password' => '密码为6到18位大小写字母和数字组合',
            ];
            $datas = [
                'password' => $password,

            ];
            $validate = new Validate($rule,$msg);
            $result = $validate->check($datas);
            $user = User::get(['phone'=>$phone]);
            $uid = $user['id'];
            $testphone = user::get(['phone'=>$phone]);
            if( $testphone == NULL && $user !== NULL && $result == true && $password == $repassword )
            {
                $user = new User;
                $user->data([ 'phone' => $phone, 'password' => MD5($password), 'uid'=> $uid]);
                $newinsert = $user->save();
                $ID = $user->id;
                if($newinsert == 1){
                    $arr = array('userId' =>  $ID, 'phone' => $phone, 'grade'=> "0");
                    $dat = ['code' => 200, 'msg' => '注册成功',$arr];
                    return json_encode($dat, TRUE);
                }else{
                    $dat = ['code' => 200, 'msg' => '您已经注册成功,请直接登录'];
                    return json_encode($dat, TRUE);
                }
            }elseif ( $result == false) {
                $dat = ['code' => 400, 'msg' => '密码和重复密码不一致'];
                return json_encode($dat);
            } elseif( $testphone !== NULL){
                $dat = ['code' => 403, 'msg' => '此手机号码已经注册，请直接登录'];
                return json_encode($dat);
            }
        }else{
            echo "NO";
        }

    }

}